'use strict';
const path = require('path');
const fs = require('fs');
const Service = require('egg').Service;
const awaitStreamReady = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const moment = require('moment');

class CommonService extends Service {
  // 接收文件，返回静态资源地址
  async uploadFile(staicDir = "upload/") {
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    const filename = Date.now() + '' + Number.parseInt(Math.random() * 10000) + path.extname(stream.filename);
    const target = path.join(this.config.baseDir, 'app/public/', staicDir, filename);

    const writeStream = fs.createWriteStream(target);
    try {
      await awaitStreamReady(stream.pipe(writeStream));
    } catch (err) {
      await sendToWormhole(stream);
      fs.unlinkSync(target);
      throw err;
    }
    return path.join('public/', staicDir, filename);
  }

  // 删除静态资源文件
  async delStaticFile(staticPath) {
    const { ctx } = this;
    if (!staticPath) {
      return { errcode: 1, msg: "文件路径为空" };
    }
    const filePath = ctx.helper.convertStaticToAbsolutePath(staticPath);
    try {
      fs.accessSync(filePath);
    } catch (err) {
      return { errcode: 1, msg: "该文件不存在" };
    }
    fs.unlinkSync(filePath);
    return { errcode: 0 };
  }

  // async bulkDelStaticFile(fileList) {
  //   const { ctx } = this;

  // }

  // 首页信息
  async getHomeInfo() {
    const { ctx } = this;
    const resideNum = await ctx.model.Student.find({ dorm_id: { $exists: true, $ne: null } }).count();
    const containerCount = (await ctx.model.Dorm.aggregate([{ $group: { _id: "", total: { $sum: '$contain_count' } } }]))[0].total;
    const leaveSchoolCount = await ctx.model.LeaveSchool.find({
      leave_date: { $lt: Date.now() },
      goback_date: { $gt: Date.now() }
    }).count();
    const repairCount = await ctx.model.Repair.find({ repair_status: { $ne: 2 } }).count();
    const emptyCount = containerCount - resideNum;

    const last7DaysRepairData = await ctx.model.Repair.aggregate([
      { $match: { edit_date: { $gte: moment().startOf('day').valueOf() - 518400000 } } },
      {
        $group: {
          _id: {
            $subtract: [
              "$edit_date",
              {
                $mod: [
                  { $subtract: ["$edit_date", +new Date(1970, 0, 1)] },
                  1000 * 60 * 60 * 24
                ]
              }
            ]
          },
          total: { $sum: 1 }
        }
      },
      {
        $project: {
          _id: 0,
          date: "$_id",
          total: "$total"
        }
      }
    ]);

    const last7Days = [];
    const last7DaysRepair = [];
    const day = moment(Date.now() - 518400000).startOf('day');
    for (let i = 1; i <= 7; i++) {
      const curDay = day.clone();
      const curDayRepair = last7DaysRepairData.find(item => item.date === curDay.valueOf());
      last7Days.push(curDay.format('YYYY-MM-DD'));
      last7DaysRepair.push((curDayRepair && curDayRepair.total) || 0);
      day.add(1, 'day');
    }

    const resideStatus = await ctx.model.Student.aggregate([
      { $group: { _id: "$reside_status", value: { $sum: 1 } } }
    ]);
    resideStatus.forEach(item => {
      (item._id === -1) && (item.name = '未入寝');
      (item._id === 1) && (item.name = '在住');
      (item._id === 2) && (item.name = '已退寝');
    });

    return {
      errcode: 0,
      data: {
        resideNum,
        containerCount,
        leaveSchoolCount,
        repairCount,
        emptyCount,
        last7Days,
        last7DaysRepair,
        resideStatus
      }
    };
  }
}

module.exports = CommonService;
